package com.xmall.auth.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.auth.define.dict.AccountTypeEnum;
import com.xmall.auth.entity.SysAccount;
import com.xmall.auth.mapper.AccountMapper;
import com.xmall.auth.service.ISysAccountService;
import com.xmall.auth.utils.PasswordUtils;
import com.xmall.define.dto.auth.AccountDto;
import com.xmall.define.dto.auth.AccountUpdateRequest;
import com.xmall.utils.ListStreamUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysAccountServiceImpl extends ServiceImpl<AccountMapper, SysAccount> implements ISysAccountService {

    /**
     * 账户是否存在
     */
    @Override
    public Boolean exists(String account) {
        QueryWrapper query = new QueryWrapper<SysAccount>().eq("account", account);
        SysAccount result = this.getOne(query);
        return null != result;
    }

    /**
     * 保存
     */
    @Override
    public void saveEntity(AccountUpdateRequest request) {
        SysAccount sysAccount = new SysAccount();
        BeanUtils.copyProperties(request, sysAccount);
        sysAccount.setType(AccountTypeEnum.PHONE.getType());

        //初始化密码
        sysAccount.setPassword(PasswordUtils.initPassword());
        this.save(sysAccount);
    }

    /**
     * 指定用户列表账号信息
     */
    @Override
    public List<AccountDto> listByUserIds(List<Long> userIds) {
        QueryWrapper<SysAccount> query = new QueryWrapper<SysAccount>().in("user_id", userIds);
        List<SysAccount> list = this.list(query).stream()
            .sorted((pre, next) -> compareLastLoginTime(pre, next))
            .filter(ListStreamUtils.distinctByKey(sysAccount -> sysAccount.getUserId())).collect(Collectors.toList());

        //转换属性
        return list.stream().map(sysAccount -> {
            AccountDto accountDto = new AccountDto();
            BeanUtils.copyProperties(sysAccount, accountDto);
            return accountDto;
        }).collect(Collectors.toList());
    }

    /**
     * 更新最后登录时间
     */
    @Override
    public Date updateLastLoginTime(Long userId, Integer accountType) {
        Date now = new Date();
        SysAccount entity = this.getOne(new QueryWrapper<SysAccount>().eq("user_id", userId).eq("type", accountType));
        if(null != entity){
            SysAccount updateEntity = new SysAccount();
            updateEntity.setId(entity.getId());
            updateEntity.setLastLoginTime(now);
            this.updateById(updateEntity);
        }
        if(null == entity) {
            log.error("updateLastLoginTime: 系统用户不存在 {}", userId);
        }
        return now;
    }

    /**
     * 根据上次登录时间进行排序
     * 原因: account 表中相同 user_id 有多条记录，分别代表不同的登录方式
     */
    private int compareLastLoginTime(SysAccount pre, SysAccount next) {
        if(null != pre.getLastLoginTime() && null != next.getLastLoginTime()){
            return DateUtil.compare(next.getLastLoginTime(), pre.getLastLoginTime());
        }

        if(null == pre.getLastLoginTime() && null == next.getLastLoginTime()){
            return 0;
        }

        return null == pre.getLastLoginTime() ? 1 : 0;
    }


}
